package workbench.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import settings.DAO.UserDao;
import settings.domain.User;
import util.DateUtil;
import util.UUIDUtil;
import workbench.dao.ActivityDao;
import workbench.dao.CustomerDao;
import workbench.dao.TranDao;
import workbench.dao.TranHistoryDao;
import workbench.domain.Activity;
import workbench.domain.Customer;
import workbench.domain.Tran;
import workbench.domain.TranHistory;
import workbench.exception.AddTranException;
import workbench.exception.CreateTranHistoryException;
import workbench.exception.DeleteException;
import workbench.exception.UpdateException;
import workbench.service.TranService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TranServiceImpl implements TranService {
    @Autowired
    private ActivityDao activityDao;
    @Autowired
    private TranDao tranDao;
    @Autowired
    private TranHistoryDao tranHistoryDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CustomerDao customerDao;
    public List<User> getUserList(){
        List<User> list=userDao.getUserList();
        return list;
    }
    @Transactional
    public void addTran(Tran tran) throws AddTranException {
        Customer customer=customerDao.getCustomerByCompanyName(tran.getCustomerId());
        tran.setCustomerId(customer.getId());
        int count=tranDao.save(tran);
        if(count!=1){
            throw new AddTranException("添加交易失败");
        }
    }
    public Tran getTranById(String id){
        Tran tran=tranDao.getTranById(id);
        return tran;
    }
    public List<TranHistory> getTranHistoryListByTranId(String tranId){
        List<TranHistory> list = tranHistoryDao.getTranHistoryListByTranId(tranId);
        return list;
    }
    @Transactional
    public void changeStage(Tran tran) throws UpdateException, CreateTranHistoryException {
        TranHistory tranHistory=new TranHistory();
        tranHistory.setId(UUIDUtil.getUUID());
        tranHistory.setTranId(tran.getId());
        tranHistory.setCreateBy(tran.getEditBy());
        tranHistory.setCreateTime(tran.getEditTime());
        tranHistory.setExpectedDate(tran.getExpectedDate());
        tranHistory.setMoney(tran.getMoney());
        tranHistory.setStage(tran.getStage());
        int count=tranHistoryDao.save(tranHistory);
        if(count!=1){
            throw new CreateTranHistoryException("创建交易变化的历史记录失败");
        }
        count=tranDao.changeStage(tran);
        if(count!=1){
            throw new UpdateException("更新交易阶段错误");
        }
    }
    public List<Map> getCharts(){
        List<Map> list=tranDao.getCharts();
        return list;
    }
}
